var qqcs;
//功能list
var tmpList;
var gnsList;
var gnsTreeList;
//节点属性
var node_id;
var node_lx;
var node_mc;
var node_targer;
var node_xybj;
var node_dkfs;

var tmp_node;

$(function () {
    /*  只返回目标节点的第一级子节点*/
    $.extend($.fn.tree.methods, {
        getLeafChildren: function (jq, params) {
            var nodes = [];
            $(params).next().children().children("div.tree-node").each(function () {
                nodes.push($(jq[0]).tree('getNode', this));
            });
            return nodes;
        }
    });
    var str_gnsList = $('#str_gnsList').val();
    //生成list
    gnsList = $.evalJSON($('#str_gnsList').val());
    //添加根目录
    var gml = {
        "id": "0",
        "pid": "",
        "mode": "0",
        "sort": "1",
        "state": "closed",
        "text": "根目录",
        "text_real": "根目录",
        "enable": "1"
    };
    gnsList.push(gml);
    reloadGnsTree();
    //隐藏维护模块
    $('#cdwhDiv').hide();
    $('#wjjwhDiv').hide();
});

//检索菜单
function jccd() {
    node_id = null;
    node_lx = null;
    node_mc = null;
    node_targer = null;
    node_xybj = null;
    var jcnr = $('#jsnr').val();
    if ("" == jcnr) {
        //没有内容,显示全部功能树
        tmpList = JSON.parse(JSON.stringify(gnsList));
        tmpList = createGnsTreeList(tmpList);
        $('#gns_tree').tree({
            onlyLeafCheck: false,//仅叶子节点可以被选中
            checkbox: false,//复选框
            data: tmpList,
            onLoadSuccess: function () {
                $("#gns_tree").tree("collapseAll");
            },
            onClick: function (node, checked) {
                //获取树节点信息
                node_id = node.id;
                node_mc = node.text_real;
                node_lx = node.mode;
                node_targer = node.target;
                node_xybj = node.enable;
                node_dkfs = node.mode;
                if ("0" == node.mode) {
                    //文件夹
                    //清空维护模块内容
                    $('#wjj_mc').val("");
                    $('#wjj_sfqy').val("");
                    $('#wjj_mc').val(node_mc);
                    $('#wjj_sfqy').val(node_xybj);
                    //标题
                    $('#whms').empty();
                    $('#whms').append("文件夹管理");
                    //显示
                    $('#cdwhDiv').hide();
                    $('#wjjwhDiv').show();
                } else {
                    //菜单
                    //清空维护模块内容
                    $('#gnmc').val("");
                    $('#dkfs').val("");
                    $('#sfqy').val("");
                    $('#gnmc').val(node_mc);
                    $('#dkfs').val(node_dkfs);
                    $('#sfqy').val(node_xybj);
                    //标题
                    $('#whms').empty();
                    $('#whms').append("菜单维护");
                    //显示
                    $('#cdwhDiv').show();
                    $('#wjjwhDiv').hide();
                }
                //更新文件夹位置
                createWjjTreeList(gnsList, node_lx, node_id);
            }, onContextMenu: function (e, node) {
                //给结点添加右键菜单
                //阻止右键默认事件
                e.preventDefault();
                if ("0" != node.id) {
                    tmp_node = node;
                    $('#leaf').menu('show', {
                        left: e.pageX,
                        top: e.pageY
                    });
                } else {
                    tmp_node = null;
                }
            }
        });
    } else {
        var tmpList = [];
        //检索菜单
        for (var i = 0; i < gnsList.length; i++) {
            if ("0" == gnsList[i].lx) {
                continue;
            } else if (gnsList[i].text.indexOf(jcnr) == -1) {
                continue;
            }
            tmpList.push(gnsList[i]);
        }
        $('#gns_tree').tree({
            onlyLeafCheck: false,//仅叶子节点可以被选中
            checkbox: false,//复选框
            data: tmpList,
            onClick: function (node, checked) {
                //获取树节点信息
                node_id = node.id;
                node_mc = node.text_real;
                node_lx = node.mode;
                node_targer = node.target;
                node_xybj = node.enable;
                node_dkfs = node.mode;
                if ("0" == node.mode) {
                    //文件夹
                    //清空维护模块内容
                    $('#wjj_mc').val("");
                    $('#wjj_sfqy').val("");
                    $('#wjj_mc').val(node_mc);
                    $('#wjj_sfqy').val(node_xybj);
                    //标题
                    $('#whms').empty();
                    $('#whms').append("文件夹管理");
                    //显示
                    $('#cdwhDiv').hide();
                    $('#wjjwhDiv').show();
                } else {
                    //菜单
                    //清空维护模块内容
                    $('#gnmc').val("");
                    $('#dkfs').val("");
                    $('#sfqy').val("");
                    $('#gnmc').val(node_mc);
                    $('#dkfs').val(node_dkfs);
                    $('#sfqy').val(node_xybj);
                    //标题
                    $('#whms').empty();
                    $('#whms').append("菜单维护");
                    //显示
                    $('#cdwhDiv').show();
                    $('#wjjwhDiv').hide();
                }
                //更新文件夹位置
                createWjjTreeList(gnsList, node_lx, node_id);
            }, onContextMenu: function (e, node) {
            }
        });
    }
}

//更新文件夹功能树
function createWjjTreeList(gnlist, mode, gnid) {
    $('#cdwz').combotree('clear');
    $('#wjjwz').combotree('clear');
    var ls_list = JSON.parse(JSON.stringify(gnlist));
    // ls_list.push({
    //     "id": "0",
    //     "text": "根目录",
    //     "text_real": "根目录",
    //     "enable": "1",
    //     "state": "open",
    //     "mode": "0",
    //     "pid": ""
    // });
    var tmpList = [];
    var obj;
    var obj2;
    for (var i = 0; i < ls_list.length; i++) {
        obj = ls_list[i];
        if ("0" != obj.mode) {
            //仅限文件夹
            continue;
        }
        if ("0" == mode && gnid == obj.id) {
            //修改文件夹路径时，不显示自己下面的文件夹
            continue;
        }
        if ("" == obj.pid || null == obj.pid) {
            tmpList.push(ls_list[i]);
        } else {
            for (var j = 0; j < ls_list.length; j++) {
                obj2 = ls_list[j];
                if (obj.pid == obj2.id) {
                    if (!obj2.hasOwnProperty("children")) {
                        obj2.children = [];
                    }
                    obj2.children.push(obj);
                    break;
                }
            }
        }
    }
    //2个combotree加载同一个对象，第一个会失效。这里再生成一个对象避免出问题。
    var ls_list = JSON.parse(JSON.stringify(tmpList));
    $('#cdwz').combotree('loadData', tmpList);
    $('#wjjwz').combotree('loadData', ls_list);
}

//根据功能列表生成功能树
function createGnsTreeList(gnlist) {
    var tmpList = [];
    var obj;
    var obj2;
    for (var i = 0; i < gnlist.length; i++) {
        obj = gnlist[i];
        if ("" == obj.pid || null == obj.pid) {
            tmpList.push(gnlist[i]);
        } else {
            for (var j = 0; j < gnlist.length; j++) {
                obj2 = gnlist[j];
                if (obj.pid == obj2.id) {
                    if (!obj2.hasOwnProperty("children")) {
                        obj2.children = [];
                    }
                    obj2.children.push(obj);
                    break;
                }
            }
        }
    }
    return tmpList;
}

//新增文件夹
function xzwjj() {
    var ls_mc = $('#new_wjj_mc').val();
    var ls_zt = $('#wjj_sfqy').val();
    if (null == node_id || "" == node_id) {
        innerToast.warn("请先选择父节点后再操作!");
        return;
    } else if ("" == ls_mc) {
        innerToast.warn("名称不能为空!");
        return;
    } else if ("" == ls_zt) {
        innerToast.warn("是否启用不能为空!");
        return;
    }
    qqcs = {
        "pid": node_id, "mc": ls_mc, "zt": ls_zt
    };
    openProgress();
    $.ajax({
        url: "/portal/admin/editfunction/addWjj.do",
        data: qqcs,
        type: "post",
        timeout: sys_timeout,
        dataType: "json",
        async: false,
        error: function (XMLHttpRequest, textStatus) {
            closeProgress();
            innerToast.warn("抱歉，系统暂时无法访问,请稍后再试");
            console.log(textStatus);
        },
        success: function (respText) {
            closeProgress();
            if (checkResponse(respText)) {
                var newnodeid = respText.repData.id;
                var xh = respText.repData.xh;
                innerToast.info("操作成功!");
                //新增功能树
                addGnsList(newnodeid, ls_mc, ls_zt, node_targer, node_id, xh);
            }
            else {
                innerToast.warn(respText.msg);
            }
        }
    });
}

//修改位置
function xgwz(lx) {
    var newpid;
    if ("1" == lx) {
        //修改菜单
        newpid = $('#cdwz').val();
    } else {
        //修改文件夹
        newpid = $('#wjjwz').val();
    }
    if ("" == newpid) {
        innerToast.warn("请选择调整位置！");
        return;
    }
    var qqcs = {"pid": newpid, "id": node_id};
    openProgress();
    $.ajax({
        url: "/portal/admin/editfunction/updateGnLj.do",
        data: qqcs,
        type: "post",
        timeout: sys_timeout,
        dataType: "json",
        async: false,
        error: function (XMLHttpRequest, textStatus) {
            closeProgress();
            innerToast.warn("抱歉，系统暂时无法访问,请稍后再试");
            console.log(textStatus);
        },
        success: function (respText) {
            closeProgress();
            if (checkResponse(respText)) {
                innerToast.info("操作成功!");
                //更新原数据
                for (var i = 0; i < gnsList.length; i++) {
                    if (node_id == gnsList[i].id) {
                        gnsList[i].pid = newpid;
                        break;
                    }
                }
                reloadGnsTree();
            }
            else {
                innerToast.warn(respText.msg);
            }
        }
    });
}

//文件夹修改
function xgwjj() {
    var ls_mc = $('#wjj_mc').val();
    var ls_zt = $('#wjj_sfqy').val();
    var ls_wjjwz = $('#wjjwz').val();
    if ("" == ls_mc) {
        innerToast.warn("名称不能为空!");
        return;
    } else if ("" == ls_zt) {
        innerToast.warn("是否启用不能为空!");
        return;
    } else if ("0" == node_id) {
        innerToast.warn("根目录无法修改!");
        return;
    }
    qqcs = {
        "id": node_id, "mc": ls_mc, "zt": ls_zt, "wjjwz": ls_wjjwz
    };
    openProgress();
    $.ajax({
        url: "/portal/admin/editfunction/updateWjj.do",
        data: qqcs,
        type: "post",
        timeout: sys_timeout,
        dataType: "json",
        async: false,
        error: function (XMLHttpRequest, textStatus) {
            closeProgress();
            innerToast.warn("抱歉，系统暂时无法访问,请稍后再试");
            console.log(textStatus);
        },
        success: function (respText) {
            closeProgress();
            if (checkResponse(respText)) {
                innerToast.info("操作成功!");
                if ("" != ls_wjjwz) {
                    //更新原数据
                    for (var i = 0; i < gnsList.length; i++) {
                        if (node_id == gnsList[i].id) {
                            gnsList[i].pid = ls_wjjwz;
                            break;
                        }
                    }
                }
                //更新原数据及功能树
                refreshGnsList(node_id, ls_mc, ls_zt, node_targer);
                reloadGnsTree();
                //展开当前菜单层级
                var newPnode = $('#gns_tree').tree('find', node_id);
                $('#gns_tree').tree('expandTo', newPnode.target);
            }
            else {
                innerToast.warn(respText.msg);
            }
        }
    });
}

//修改菜单信息
function xgcdxx() {
    var ls_mc = $('#gnmc').val();
    var ls_dkfs = $('#dkfs').val();
    var ls_sfqy = $('#sfqy').val();
    var ls_cdwz = $('#cdwz').val();
    if ("" == ls_mc) {
        innerToast.warn("名称不能为空!");
        return;
    } else if ("" == ls_dkfs) {
        innerToast.warn("打开方式不能为空!");
        return;
    } else if ("" == ls_sfqy) {
        innerToast.warn("是否启用不能为空!");
        return;
    }
    qqcs = {
        "id": node_id, "mc": ls_mc, "zt": ls_sfqy, "dkfs": ls_dkfs, "cdwz": ls_cdwz
    };
    openProgress();
    $.ajax({
        url: "/portal/admin/editfunction/updateCdxx.do",
        data: qqcs,
        type: "post",
        timeout: sys_timeout,
        dataType: "json",
        async: false,
        error: function (XMLHttpRequest, textStatus) {
            closeProgress();
            innerToast.warn("抱歉，系统暂时无法访问,请稍后再试");
            console.log(textStatus);
        },
        success: function (respText) {
            closeProgress();
            if (checkResponse(respText)) {
                innerToast.info("操作成功!");
                if ("" != ls_cdwz) {
                    //更新原数据
                    for (var i = 0; i < gnsList.length; i++) {
                        if (node_id == gnsList[i].id) {
                            gnsList[i].pid = ls_cdwz;
                            break;
                        }
                    }
                }
                //更新原数据及功能树
                refreshGnsList(node_id, ls_mc, ls_sfqy, ls_dkfs, node_targer);
                reloadGnsTree();
                //展开当前菜单层级
                var newPnode = $('#gns_tree').tree('find', node_id);
                $('#gns_tree').tree('expandTo', newPnode.target);
            }
            else {
                innerToast.warn(respText.msg);
            }
        }
    });
}

//更新list及节点
function refreshGnsList(id, mc, xybj, dkfs, target) {
    var ztmc = "";
    if ("0" == xybj) {
        ztmc = "（停用）";
    } else {
        ztmc = "（启用）";
    }
    //更新原数据
    for (var i = 0; i < gnsList.length; i++) {
        if (id == gnsList[i].id) {
            gnsList[i].xybj = xybj;
            gnsList[i].gnmc = mc;
            gnsList[i].text = gnsList[i].gnmc + ztmc;
            gnsList[i].dkfs = dkfs;
            break;
        }
    }
    //更新树
    var tmp_node = $('#gns_tree').tree('getNode', node_targer);
    if (tmp_node) {
        $('#gns_tree').tree('update', {
            target: tmp_node.target,
            text: mc + ztmc,
            gnmc: mc,
            xybj: xybj,
            dkfs: dkfs
        });
    }
}

//新增list及节点(文件夹)
function addGnsList(id, mc, xybj, target, pid, xh) {
    var ztmc = "";
    if ("0" == xybj) {
        ztmc = "（停用）";
    } else {
        ztmc = "（启用）";
    }
    //新增list
    var new_node = {
        "id": id,
        "text": mc + ztmc,
        "text_real": mc,
        "pid": pid,
        "mode": "0",
        "enable": xybj,
        "iconCls": null,
        "state": "closed",
        "sort": xh,
        "children": []
    };
    gnsList.push(new_node);
    //更新树
    //获取父节点
    var tmp_node = $('#gns_tree').tree('getNode', target);
    if (tmp_node) {
        //增加子节点
        $('#gns_tree').tree('append', {
            parent: target,
            data: new_node
        });
    }
}

function openProgress() {
    $.messager.progress({
        title: '提示',
        msg: '请稍候……',
        text: ''
    });
}

function closeProgress() {
    $.messager.progress('close');
}

function reloadGnsTree() {
    tmpList = JSON.parse(JSON.stringify(gnsList));
    //生成tree格式
    gnsTreeList = createGnsTreeList(tmpList);
    $('#gns_tree').tree({
        onlyLeafCheck: false,
        checkbox: false,
        data: gnsTreeList,
        onLoadSuccess: function () {
            $("#gns_tree").tree("collapseAll");
        },
        onClick: function (node, checked) {
            //获取树节点信息
            node_id = node.id;
            node_mc = node.text_real;
            node_lx = node.mode;
            node_targer = node.target;
            node_xybj = node.enable;
            node_dkfs = node.mode;
            if ("0" == node.mode) {
                //文件夹
                //清空维护模块内容
                $('#wjj_mc').val("");
                $('#wjj_sfqy').val("");
                $('#wjj_mc').val(node_mc);
                $('#wjj_sfqy').val(node_xybj);
                //标题
                $('#whms').empty();
                $('#whms').append("文件夹管理")
                //显示
                $('#cdwhDiv').hide();
                $('#wjjwhDiv').show();
            } else {
                //菜单
                //清空维护模块内容
                $('#gnmc').val("");
                $('#dkfs').val("");
                $('#sfqy').val("");
                $('#gnmc').val(node_mc);
                $('#dkfs').val(node_dkfs);
                $('#sfqy').val(node_xybj);
                //标题
                $('#whms').empty();
                $('#whms').append("菜单维护")
                //显示
                $('#cdwhDiv').show();
                $('#wjjwhDiv').hide();
            }
            //更新文件夹位置
            createWjjTreeList(gnsList, node_lx, node_id);
        }, onContextMenu: function (e, node) {
            //给结点添加右键菜单
            //阻止右键默认事件
            e.preventDefault();
            if ("0" != node.id) {
                tmp_node = node;
                $('#leaf').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            } else {
                tmp_node = null;
            }
        }
    });
}

//菜单上移
function upNode() {
    if (null == tmp_node) {
        innerToast.warn("请先选择菜单节点!");
        return;
    }
    var tmp_ParentNode = $('#gns_tree').tree('getParent', tmp_node.target);
    if (null == tmp_ParentNode) {
        innerToast.warn("无法获取父节点，本次操作失败!");
        return;
    }
    var tmp_ParentAllChilds = $('#gns_tree').tree('getLeafChildren', tmp_ParentNode.target);
    if (null == tmp_ParentAllChilds) {
        innerToast.warn("无法获取同级菜单，本次操作失败!");
        return;
    }
    if (0 == tmp_ParentAllChilds.length) {
        innerToast.warn("无法获取同级菜单，本次操作失败!");
        return;
    }
    if (1 == tmp_ParentAllChilds.length) {
        innerToast.warn("同级目录仅有一个菜单，本次操作失败!");
        return;
    }
    var sjNodeXH = null;
    for (var i = 0; i < tmp_ParentAllChilds.length; i++) {
        if (tmp_node.id == tmp_ParentAllChilds[i].id) {
            sjNodeXH = i - 1;
            break;
        }
    }
    if (null == sjNodeXH) {
        innerToast.warn("无法获取上一个菜单，本次操作失败!");
        return;
    }
    if (-1 == sjNodeXH) {
        innerToast.warn("菜单已经是第一个了，本次操作失败!");
        return;
    }
    //构建新上级node的新属性
    var SjNode = {
        "id": tmp_node.id,
        "pid": tmp_node.pid,
        "text_real": tmp_node.text_real,
        "text": tmp_node.text,
        "sort": tmp_ParentAllChilds[sjNodeXH].sort,
        "mode": tmp_node.mode,
        "enable": tmp_node.enable,
        "state": tmp_node.state
    };
    //构建新下级node的新属性
    var XjNode = {
        "id": tmp_ParentAllChilds[sjNodeXH].id,
        "pid": tmp_ParentAllChilds[sjNodeXH].pid,
        "text_real": tmp_ParentAllChilds[sjNodeXH].text_real,
        "text": tmp_ParentAllChilds[sjNodeXH].text,
        "sort": tmp_node.sort,
        "mode": tmp_ParentAllChilds[sjNodeXH].mode,
        "enable": tmp_ParentAllChilds[sjNodeXH].enable,
        "state": tmp_ParentAllChilds[sjNodeXH].state
    };
    qqcs = {"node1": SjNode.id, "node2": XjNode.id};
    //调用后台修改:
    openProgress();
    $.ajax({
        url: "/portal/admin/editfunction/upNodeWz.do",
        data: qqcs,
        type: "post",
        timeout: sys_timeout,
        dataType: "json",
        async: false,
        error: function (XMLHttpRequest, textStatus) {
            closeProgress();
            innerToast.warn("抱歉，系统暂时无法访问,请稍后再试");
            console.log(textStatus);
        },
        success: function (respText) {
            closeProgress();
            if (checkResponse(respText)) {
                innerToast.info("操作成功!");
                //原数据里的上下级替换
                $.each(gnsList, function (index, item) {
                    if (item.id == SjNode.id) {
                        gnsList.splice(index, 1, XjNode);
                        return false;
                    }
                });
                $.each(gnsList, function (index, item) {
                    if (item.id == XjNode.id) {
                        gnsList.splice(index, 1, SjNode);
                        return false;
                    }
                });
                reloadGnsTree();
                //展开当前菜单层级
                var newPnode = $('#gns_tree').tree('find', tmp_node.id);
                $('#gns_tree').tree('expandTo', newPnode.target);
            }
            else {
                innerToast.warn(respText.msg);
            }
        }
    });
}

//菜单下移
function downNode() {
    if (null == tmp_node) {
        innerToast.warn("请先选择菜单节点!");
        return;
    }
    var tmp_ParentNode = $('#gns_tree').tree('getParent', tmp_node.target);
    if (null == tmp_ParentNode) {
        innerToast.warn("无法获取父节点，本次操作失败!");
        return;
    }
    var tmp_ParentAllChilds = $('#gns_tree').tree('getLeafChildren', tmp_ParentNode.target);
    if (null == tmp_ParentAllChilds) {
        innerToast.warn("无法获取同级菜单，本次操作失败!");
        return;
    }
    if (0 == tmp_ParentAllChilds.length) {
        innerToast.warn("无法获取同级菜单，本次操作失败!");
        return;
    }
    if (1 == tmp_ParentAllChilds.length) {
        innerToast.warn("同级目录仅有一个菜单，本次操作失败!");
        return;
    }
    var dqNodeXH = null;
    for (var i = 0; i < tmp_ParentAllChilds.length; i++) {
        if (tmp_node.id == tmp_ParentAllChilds[i].id) {
            dqNodeXH = i;
            break;
        }
    }
    if (dqNodeXH + 1 == tmp_ParentAllChilds.length) {
        innerToast.warn("已经是最后一个菜单了，无法下移!");
        return;
    }
    var xjNodeXH = dqNodeXH + 1;
    //构建新下级node的新属性
    var XjNode = {
        "id": tmp_node.id,
        "pid": tmp_node.pid,
        "text_real": tmp_node.text_real,
        "text": tmp_node.text,
        "sort": tmp_ParentAllChilds[xjNodeXH].sort,
        "mode": tmp_node.mode,
        "enable": tmp_node.enable,
        "state": tmp_node.state
    };
    //构建新下级node的新属性
    var SjNode = {
        "id": tmp_ParentAllChilds[xjNodeXH].id,
        "pid": tmp_ParentAllChilds[xjNodeXH].pid,
        "text_real": tmp_ParentAllChilds[xjNodeXH].text_real,
        "text": tmp_ParentAllChilds[xjNodeXH].text,
        "sort": tmp_node.sort,
        "mode": tmp_ParentAllChilds[xjNodeXH].mode,
        "enable": tmp_ParentAllChilds[xjNodeXH].enable,
        "state": tmp_ParentAllChilds[xjNodeXH].state
    };
    qqcs = {"node1": SjNode.id, "node2": XjNode.id};
    //调用后台修改:
    openProgress();
    $.ajax({
        url: "/portal/admin/editfunction/upNodeWz.do",
        data: qqcs,
        type: "post",
        timeout: sys_timeout,
        dataType: "json",
        async: false,
        error: function (XMLHttpRequest, textStatus) {
            closeProgress();
            innerToast.warn("抱歉，系统暂时无法访问,请稍后再试");
            console.log(textStatus);
        },
        success: function (respText) {
            closeProgress();
            if (checkResponse(respText)) {
                innerToast.info("操作成功!");
                //原数据里的上下级替换
                $.each(gnsList, function (index, item) {
                    if (item.id == SjNode.id) {
                        gnsList.splice(index, 1, XjNode);
                        return false;
                    }
                });
                $.each(gnsList, function (index, item) {
                    if (item.id == XjNode.id) {
                        gnsList.splice(index, 1, SjNode);
                        return false;
                    }
                });
                reloadGnsTree();
                //展开当前菜单层级
                var newPnode = $('#gns_tree').tree('find', tmp_node.id);
                $('#gns_tree').tree('expandTo', newPnode.target);
            }
            else {
                innerToast.warn(respText.msg);
            }
        }
    });
}